package org.dh2580.delay.queue.bean;

import java.util.concurrent.TimeUnit;

import javax.sql.DataSource;

import org.dh2580.delay.queue.bean.db.DBUtil;
import org.dh2580.delay.queue.bean.except.SendMsgException;

/**
 * @Author: hao.deng
 * @Date: 2019/5/14-下午7:47
 */
public class MsgSender {

    private static final String ADD_MSG_SQL_TPL = "INSERT INTO tb_delay_msg_queue(route_key,msg,ttl) VALUES(?,?,?);";

    private DataSource dataSource;

    public MsgSender(DataSource dataSource) {
        this.dataSource = dataSource;

        DBUtil.setDataSource(dataSource);
    }

    public void send(String routeKey, String msg, long ttl, TimeUnit timeUnit) {
        try {
            DBUtil.execute(ADD_MSG_SQL_TPL, routeKey, msg, timeUnit.toMillis(ttl) + System.currentTimeMillis());

        } catch (Exception e) {
            throw new SendMsgException("发送消息异常", e);
        }
    }
}
